package yf.mall.component.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.yf.response.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import yf.mall.component.helper.ProductHelper;
import yf.mall.dysdk.model.product.DyProduct;
import yf.mall.dysdk.model.product.DyProductList;
import yf.mall.dysdk.model.DyToken;
import yf.mall.dysdk.model.common.DyResponse;
import yf.mall.dysdk.model.product.StoreAddResponse;
import yf.mall.dysdk.model.product.StoreResult;
import yf.mall.dysdk.model.request.DyProductSearchRequest;
import yf.mall.dysdk.service.DyAllianceApiService;
import yf.mall.entity.AppFavoriteEntity;
import yf.mall.entity.KolProductEntity;
import yf.mall.entity.KolProductStatEntity;
import yf.mall.entity.KolShopEntity;
import yf.mall.entity.custom.KolProductParam;
import yf.mall.enums.app.AppCollectTypeEnum;
import yf.mall.service.app.*;
import yf.mall.vo.app.common.DataResult;
import yf.mall.vo.app.common.ListResult;
import yf.mall.vo.app.request.ProductListRequest;
import yf.mall.vo.app.product.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class AppProductComponent {

    @Resource
    private KolShopService kolShopService;

    @Resource
    private KolProductService kolProductService;

    @Resource
    private DyAllianceApiService dyAllianceApiService;

    @Resource
    private AppDyAuthCompoent appDyAuthCompoent;

    @Resource
    private AppFavoriteService appFavoriteService;

    @Resource
    private AppProductMaterialService appProductMaterialService;

    public KolProductVo getKolProductDetail(Long pid, Long userId) {

        KolProductEntity kolProduct = kolProductService.get(pid);

        KolProductVo kolProductVo = ProductHelper.convertProductEnityToVo(kolProduct);

        fillShopInfo(Collections.singletonList(kolProductVo), Collections.singletonList(kolProduct));

        fillCollect(Collections.singletonList(kolProductVo), Collections.singletonList(kolProduct), userId);

        return kolProductVo;
    }


    public TotalStatisticsVo getKolProductStatistics(Long pid, Date begin, Date end) {
        DyToken token = appDyAuthCompoent.getDefaultToken();
        if (token == null) {
            return null;
        }
        List<DyProduct> dyProducts = dyAllianceApiService.productDetail(token, Collections.singletonList(pid), true, true, true);

        if (dyProducts.isEmpty()) {
            return null;
        }
        DyProduct dyProduct = dyProducts.get(0);

        return ProductHelper.convertStatistics(dyProduct, begin, end);
    }

    public TotalStatisticsVo getKolProduct24Stat(Long pid, Integer beforeHour) {
        KolProductStatEntity kolProductStatEntity = kolProductService.findStatByProductId(pid);
        return ProductHelper.convert24Stat(kolProductStatEntity, beforeHour);
    }


    public ListResult<KolProductVo> getKolProductList(ProductListRequest request, Long loginUserId) {
        KolProductParam query = buildQuery(request);
        PageInfo<KolProductEntity> page = kolProductService.page(query);
        List<KolProductEntity> products = page.getList();
        if (products.isEmpty()) {
            return new ListResult<>(Collections.emptyList(), false);
        }


        List<KolProductVo> productVos = ProductHelper.productEntityListToVo(products);
        fillShopInfo(productVos, products);
        fillMaterialStatus(productVos, products);
        return new ListResult<>(productVos, page.isHasNextPage());
    }

    public ListResult<KolProductVo> getRealTimeKolProductList(ProductListRequest request, Long loginUserId) {
        DyProductSearchRequest paramMap = buildDyParam(request);
        DyProductList dyProductList = dyAllianceApiService.productsSearch(appDyAuthCompoent.getMasterTokenByUser(loginUserId), paramMap);
        List<DyProduct> products = dyProductList.getProducts();
        if (products.isEmpty()) {
            return new ListResult<>(Collections.emptyList(), false);
        }
        List<KolProductEntity> kolProductEntities = ProductHelper.dyProductListConvertToEntity(products);
        List<KolProductVo> productVos = ProductHelper.productEntityListToVo(kolProductEntities);
        fillShopInfo(productVos, kolProductEntities);
        return new ListResult<>(productVos, dyProductList.getTotal() > request.getPage() * request.getLimit());
    }

    public DataResult storeAdd(Long loginUserId, Long productId, String displayId) {
        DyToken dyToken = appDyAuthCompoent.getDyTokenByUserIdAndDisplayId(loginUserId, displayId);
        if (dyToken == null) {
            return new DataResult(false, "您还未进行抖音授权，请先进行抖音授权");
        }
        StoreAddResponse dyResponse = dyAllianceApiService.storeAdd(dyToken, Collections.singletonList(productId), false, null, false);

        if (dyResponse.getErrorCode() != 0 || dyResponse.getTotal() <= 0) {
            return new DataResult(false, "系统异常，请换个商品");
        }
        StoreResult result = dyResponse.getResults().get(0);
        if (result.getErrorCode() != 0) {
            return new DataResult(false, result.getErrorMsg());
        }
        return new DataResult(true, "success");
    }


    private DyProductSearchRequest buildDyParam(ProductListRequest request) {
        DyProductSearchRequest dyRequest = new DyProductSearchRequest();
        dyRequest.setTitle(request.getKeywords());
        dyRequest.setFirstCids(Stream.of(request.getLv1().split(",")).map(Integer::parseInt).collect(Collectors.toList()));
        dyRequest.setSecondCids(Stream.of(request.getLv2().split(",")).map(Integer::parseInt).collect(Collectors.toList()));
//        dyRequest.setThirdCids();
//        dyRequest.setPriceMin();
//        dyRequest.setPriceMax();
//        dyRequest.setSellNumMin();
//        dyRequest.setSellNumMax();
//        dyRequest.setSearchType();
//        dyRequest.setSortType();
        dyRequest.setPage(request.getPage());
        dyRequest.setPageSize(request.getLimit());
//        dyRequest.setShareStatus();
//        dyRequest.setActivityId();
//        dyRequest.setMixActivityId();
        dyRequest.setSearchType(0);
        dyRequest.setSortType(0);
        return dyRequest;
    }


    private void fillMaterialStatus(List<KolProductVo> productVos, List<KolProductEntity> kolProductEntities) {
        List<Long> productIds = kolProductEntities.stream().map(KolProductEntity::getId).collect(Collectors.toList());
        Map<Long, Integer> pidCountMap = appProductMaterialService.getPidCountMap(productIds);
        productVos.forEach(productVo -> {
            Long pid = Long.parseLong(productVo.getProductId());
            if (pidCountMap.containsKey(pid)) {
                productVo.setHasMeterial(pidCountMap.get(pid) > 0);
            }
        });
    }

    private void fillShopInfo(List<KolProductVo> productVos, List<KolProductEntity> products) {
        List<Long> shopIds = products.stream().map(KolProductEntity::getShopId).distinct().collect(Collectors.toList());
        Map<Long, Long> productShopRelateMap = products.stream().collect(Collectors.toMap(KolProductEntity::getId, KolProductEntity::getShopId));

        Map<Long, KolShopEntity> shopMap = getKolShopMap(shopIds);
        productVos.forEach(product -> {
            Long shopId = productShopRelateMap.get(Long.parseLong(product.getPid()));
            if (!shopMap.containsKey(shopId)) {
                product.setShop(createDefaultShop());
            }
            KolShopEntity kolShop = shopMap.get(shopId);
            product.setShop(ProductHelper.convertShopEntityToVo(kolShop));
        });
    }

    private void fillCollect(List<KolProductVo> productVos, List<KolProductEntity> productEntities, Long userId) {
        List<Long> productIds = productEntities.stream().map(KolProductEntity::getId).collect(Collectors.toList());
        List<AppFavoriteEntity> favoriteEntities = appFavoriteService.findFavoriteByRefId(userId, AppCollectTypeEnum.PRODUCT.getKey(), productIds);
        List<Long> favoriteIds = favoriteEntities.stream().filter(entity -> Objects.equals(1, entity.getStatus())).map(AppFavoriteEntity::getRefId).distinct().collect(Collectors.toList());
        productVos.forEach(productVo -> {
            if (favoriteIds.contains(Long.parseLong(productVo.getProductId()))) {
                productVo.setCollect(true);
            } else {
                productVo.setCollect(false);
            }
        });
    }

    @NotNull
    private Map<Long, KolShopEntity> getKolShopMap(List<Long> shopIds) {
        if (CollectionUtils.isEmpty(shopIds)) {
            return Collections.emptyMap();
        }
        List<KolShopEntity> kolShops = kolShopService.listByIds(shopIds);
        Map<Long, KolShopEntity> shopMap = kolShops.stream().collect(Collectors.toMap(KolShopEntity::getId, Function.identity()));
        return shopMap;
    }

    private KolProductParam buildQuery(ProductListRequest request) {
        KolProductParam param = new KolProductParam();
        param.setPageSize(request.getLimit());
        param.setPageNumber(request.getPage());
        if (StringUtils.isNotBlank(request.getKeywords())) {
            param.setTitle("%" + request.getKeywords() + "%");
        }
        if (request.getMarketType() != null) {
            param.setMarketType(request.getMarketType());
        }
        if (request.getType() != null) {
            param.setMaterialType(request.getType());
        }
        if (StringUtils.isNotBlank(request.getLv1())) {
            param.setFirstCid(Stream.of(request.getLv1().split(",")).map(Integer::parseInt).collect(Collectors.toList()));
        }
        if (StringUtils.isNotBlank(request.getLv2())) {
            param.setSecondCid(Stream.of(request.getLv2().split(",")).map(Integer::parseInt).collect(Collectors.toList()));
        }
        if (request.getSalesType() != null) {
            switch (request.getSalesType()) {
                case 1:
                    param.setOrderBy("sale_of_today desc");
                    break;
                case 2:
                    param.setOrderBy("sale_of_7 desc");
                    break;
                case 3:
                    param.setOrderBy("order_num desc");
                    break;
                case 4:
                    param.setOrderBy("sales desc");
                    break;
                default:
                    break;
            }
            // TODO 待实现
        }
        //没有排序 默认时间倒序
        if (StringUtils.isBlank(param.getOrderBy())) {
            param.setOrderBy("add_time desc");
        }
        param.setProductIds(request.getProductIds());
        param.setHasMaterial(request.isHasMaterial());
        return param;
    }

    private KolShopVo createDefaultShop() {
        KolShopVo kolShopVo = new KolShopVo();
        kolShopVo.setLogisticsRating("");
        kolShopVo.setLogisticsScore("0");
        kolShopVo.setLogo("");
        kolShopVo.setName("");
        kolShopVo.setProductRating("");
        kolShopVo.setProductScore("0");
        kolShopVo.setScore(0);
        kolShopVo.setScoreRating("");
        kolShopVo.setShopRating("");
        kolShopVo.setShopScore("0");
        return kolShopVo;
    }

}
